//
//  TextView+Emoticon.swift
//  01表情键盘
//
//  Created by 龚欣 on 15/7/8.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit

extension UITextView{
    func insertEmoticon(emoticon : Emoticon){
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
        }
        
        if emoticon.removeButton {
            deleteBackward()
            return
        }
        
        if emoticon.chs != nil {
            
            let imageText = EmoticonAttachment.emoticonString(emoticon, font: font!)
            
            let strM = NSMutableAttributedString(attributedString: attributedText)
            
            strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            let range = selectedRange
            
            attributedText = strM
            
            selectedRange = NSMakeRange(range.location + 1, 0)
            
            delegate!.textViewDidChange!(self)
        }
    }

    func emoticonText() -> String {
        var strM = String()
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.chs!
            }else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
}